import os
import urllib
import time
import json
import searchinc
import constant
import re


def search_media(name, lang, limit, media_type, year):
    page = 1

    if media_type == 'movie':
        search_func = _get_movie_search_data

    elif media_type == 'tvshow' or media_type == 'tvshow_episode':
        search_func = _get_movie_search_data
    else:
        return []

    search_data = search_func(name, lang, year, page)

    if not search_data.get('count'):
        return []

    total = search_data['count']
    total_result = parse_search_data(search_data, lang, limit)

    while (len(total_result) < limit) and len(total_result) < total:
        page += 1
        search_data = search_func(name, lang, year, page)
        one_page_result = parse_search_data(search_data, lang, limit)
        total_result.extend(one_page_result)

    if (0 < limit) and (limit < len(total_result)):
        total_result = total_result[0:limit]

    return total_result


def parse_search_data(search_data, lang, limit):
    if not search_data.get('html'):
        return []

    result = []
    html = search_data['html']
    pattern = re.compile(r'<a href=\"\/movie\/subject\/(\d+)\/\">')
    fin = pattern.findall(html)
    if len(fin) > 0:
        for item in fin:
            data = {'id': item, 'lang': lang}
            result.append(data)
            if (0 < limit) and (limit <= len(result)):
                break
    return result


def _get_movie_search_data(name, lang, year, page):
    nameEncode = urllib.parse.quote_plus(name)
    page = page - 1
    # search
    cache_path = searchinc.get_plugin_data_directory(
        constant.PLUGINID) + '/movie/query/' + nameEncode + '_' + str(year) + '_' + '_' + str(page) + '.json'
    url = constant.SEARCH_URL + '/j/search/?q=' + nameEncode + '&t=1002&p=' + str(page)
    result = _get_data_from_cache_or_download(url, cache_path, constant.DEFAULT_EXPIRED_TIME)
    return json.loads(result)


def get_movie_detail_data(item_id, lang, expired_time):
    cache_path = searchinc.get_plugin_data_directory(
        constant.PLUGINID) + '/movie/' + str(item_id) + '/' + lang + '.json'

    url = constant.THEMOVIEDB_URL + '/subject/' + str(item_id)
    return _get_data_from_cache_or_download(url, cache_path, expired_time)


def get_tv_episode_detail_data(item_id, lang, season, episode):
    episode_cache_pattern = '_e' + str(episode) if episode is not None else ''
    cache_path = searchinc.get_plugin_data_directory(
        constant.PLUGINID) + "/tv/" + str(item_id) + "/" + lang + '_s' + str(season) + episode_cache_pattern + ".json"
    url = constant.THEMOVIEDB_URL + '/subject/' + str(item_id) + '/episode/' + str(episode)
    return _get_data_from_cache_or_download(url, cache_path, constant.DEFAULT_EXPIRED_TIME)


def _get_data_from_cache_or_download(url, cache_path, expired_time):
    result = None

    if os.path.exists(cache_path):
        last_modify_time = os.path.getmtime(cache_path)

        if expired_time > (time.time() - last_modify_time):
            result = searchinc.load_local_cache(cache_path)

            if result != None:
                return result

        os.remove(cache_path)

    else:
        directory_path = os.path.dirname(cache_path)
        if not os.path.exists(directory_path):
            oldmask = os.umask(0)
            os.makedirs(directory_path, 0o755)
            os.umask(oldmask)
    download_success = searchinc.http_get_download(url, None, 'GET', None, cache_path)

    if download_success == 200:
        result = searchinc.load_local_cache(cache_path)

    return result


def _parse_translation(translationData):
    langList = []
    for item in translationData['translations']:
        iso639 = item['iso_639_1']
        iso3166 = item['iso_3166_1']
        langList.append(iso639 + '-' + iso3166)
    return langList


def _convert_to_api_lang(lang):
    langDict = {
        'chs': 'zh-CN', 'cht': 'zh-TW', 'csy': 'cs-CZ', 'dan': 'da-DK',
        'enu': 'en-US', 'fre': 'fr-FR', 'ger': 'de-DE', 'hun': 'hu-HU',
        'ita': 'it-IT', 'jpn': 'ja-JP', 'krn': 'ko-KR', 'nld': 'nl-NL',
        'nor': 'no-NO', 'plk': 'pl-PL', 'ptb': 'pt-BR', 'ptg': 'pt-PT',
        'rus': 'ru-RU', 'spn': 'es-ES', 'sve': 'sv-SE', 'trk': 'tr-TR',
        'tha': 'th-TH'
    }
    if lang in langDict.keys():
        return langDict[lang]

    if lang in langDict.values():
        return lang
    return None
